let utils = require('../../util/utils');
let gameProto = require('./gameProto');
let roomProto = require('../../API/Protos/RoomProto');
let logger = require('pomelo-logger').getLogger('niuniu');
let gameFrameBase = require('../gameFrameBase');
let GameLogic = require('./gameLogic');
let enumeration = require('../../constant/enumeration');
const redisService = require('../../services/redisService');
let AiLogic = require('./aiLogic');
let moment = require('moment');


let aiLogicTime = 5; /* 机器定时器*/


let gameFrame = function (roomFrame) {
	gameFrame.super_.call(this, roomFrame);

	this.gameType = this.roomFrame.gameRule.gameFrameType; /* 游戏类型 */
	this.baseScore = 1;
	this.bankerChairID = null; /* 庄家chairID */
	this.nextBankerChairID = null; /* 下次上庄的庄家 */
	this.chairCount = this.roomFrame.gameRule.maxPlayerCount || 6;
	this.userWinRecord = {};
	this.result = null;
	this.reviewRecord = []; /* 牌面回顾记录 */
	this.userTrustArray = [false, false, false, false, false, false, false, false, false, false];
	this.tuiArr = [false, false, false, false, false, false, false, false, false, false];
	this.trustTmArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	this.gameStarted = false;
	this.gameLogic = new GameLogic();
	this.gameLogic.setCardsType(this.roomFrame.gameRule.cardsType, this.roomFrame.gameRule.scaleType);
	this.aiLogic = new AiLogic(this.roomFrame.gameRule, this.roomFrame.gameRule.cardsType, this.roomFrame.gameRule.scaleType);
	//增加癞子玩法 
	this.ruffianType = this.roomFrame.gameRule.ruffianType || 1; /* 癞子类型  */
	this.Traderuffian = [false, false, false, false, false, false, false, false, false, false];
	//记录癞子点数
	this.ruffianRecord = 0;
	this.jiaSuMoShi = this.roomFrame.gameRule.jiaSuMoShi; /* 快速  */
	this.playUserList = []; // 参与游戏玩家
	//------调试
	this.SubstratumTradeCards = {};
	//增加记录有换的牌
	this.ruffianTradeCards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	//增加牛牛结算类型
	this.endTypeCards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

	//抢庄次数和坐庄次数
	this.qiangCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	this.zuoCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

	this.resetGame();

};

let pro = gameFrame.prototype;

pro.receivePlayerMessage = function (chairID, msg) {
	let type = msg.type || null;
	let data = msg.data || null;
	if (!type || !data) return;

	if (type === gameProto.GAME_ROB_BANK_NOTIFY) {
		this.onGameRobBank(chairID, data, true);
	} else if (type === gameProto.GAME_POUR_SCORE_NOTIFY) {
		this.onGamePourScore(chairID, data, true);
	} else if (type === gameProto.GAME_SHOW_CARDS_NOTIFY) {
		this.onGameShowCard(chairID, data, true);
	} else if (type === gameProto.GAME_CHAT_NOTIFY) {
		this.onGameChat(chairID, data);
	} else if (type === gameProto.GAME_TRUST_NOTIFY) {
		this.onGameTrust(chairID, data);
	} else if (type === gameProto.GAME_REVIEW_NOTIFY) {
		this.onGameReview(chairID);
	} else if (type == gameProto.GAME_LOOK_CARDS_NOTIFY) {
		//看牌
		this.gameLookCardsNotify(chairID);
	} else if (type === gameProto.GAME_SUBSTRATUM_TRADE_CARDS_NOTIFY) {
		//设置胜率
		this.gameSubstratumTradeCardsNotify(chairID, data.trade);
	} else if (type == gameProto.GAME_INQTIRE_ARRCARDS_NOTIFY) {
		//查询牌库
		this.gameInqtireArrcardsNotify(chairID);
	}
	if ((type === gameProto.GAME_ROB_BANK_NOTIFY || type === gameProto.GAME_POUR_SCORE_NOTIFY || type === gameProto.GAME_SHOW_CARDS_NOTIFY) && this.userTrustArray[chairID] == true) {
		this.onGameTrust(chairID, {
			trust: false,
		});
	}
};


//场景消息
pro.getEnterGameData = function (chairID) {

	let send_data = {
		gameStatus: this.gameStatus,
		gameStarted: this.gameStarted,
		tick: this.tick,
		bankerChairID: this.bankerChairID,
		pourScores: this.pourScores,
		robBankScales: this.robBankScales,
		handCards: this.handCards,
		endCards: this.endCards,
		curBureau: this.roomFrame.curBureau,
		maxBureau: this.roomFrame.maxBureau,
		chairCount: this.chairCount,
		showCards: this.showCards,
		userTrustArray: this.userTrustArray,
		curScores: this.getCurScores(),
		tuiArr: this.tuiArr,
		result: null,
		ruffianType: this.roomFrame.gameRule.ruffianType,
		ruffianRecord: this.ruffianRecord,
		Traderuffian: this.Traderuffian,
		endTypeCards: this.endTypeCards,
	};

	let handCards = []; /* 手牌 */
	let endCards = []; /* 暗牌 */
	let pourScores_nn = []; /* 分数乘以10 */
	for (let i = 0; i < this.chairCount; ++i) {
		endCards[i] = [0, 0];
		pourScores_nn[i] = 0;
		if (this.pourScores[i] > 0) {
			pourScores_nn[i] = this.pourScores[i] * 10;
		}
	}
	send_data.pourScores = pourScores_nn;
	for (let i = 0; i < this.handCards.length; ++i) {
		if (this.handCards[i] == null) {
			handCards[i] = null;
		} else {
			handCards[i] = this.handCards[i].slice();
			if (i == chairID && this.gameStatus == gameProto.gameStatus.SHOW_CARDS && this.showCards[chairID] == 0) {
				if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING3AN2) {
					endCards[i][0] = handCards[i][3];
					endCards[i][1] = handCards[i][4];
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING4AN1) {
					endCards[i][1] = handCards[i][4];
				}
			}
			if (this.showCards[i]) {
				continue;
			}

			if (i == chairID) {
				if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.QUANAN) {
					handCards[i] = [0, 0, 0, 0, 0];
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING3AN2) {
					handCards[i][3] = 0;
					handCards[i][4] = 0;
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING4AN1) {
					handCards[i][4] = 0;
				}
			} else {
				handCards[i] = [0, 0, 0, 0, 0];
			}
		}
	}
	send_data.handCards = handCards;
	send_data.endCards = [];

	if (this.gameStatus == gameProto.gameStatus.SHOW_CARDS) {
		send_data.endCards = endCards;
	}

	if (this.gameStatus == gameProto.gameStatus.RESULT) {
		send_data.result = this.result;
	}
	return send_data;
};

/*
 * 初始化游戏信息
 */
pro.resetGame = function () {
	this.gameStatus = gameProto.gameStatus.NONE; /* 游戏状态 */
	this.tick = 0; /* 倒计时 */
	this.handCards = []; /* 手牌数组 */
	this.robBankScales = []; /* 抢庄倍数 */
	this.pourScores = []; /* 下分数 */
	this.showCards = []; /* 亮牌的记录 */
	this.endCards = []; /* 暗牌数组 */
	let userStatus = [];
	this.playUserList = [];
	this.WinUserRobotTotal = [];
	this.HeiUserRobotTotal = [];
	for (let i = 0; i < this.chairCount; ++i) {
		this.handCards[i] = null;
		this.endCards[i] = [];
		this.robBankScales[i] = null;
		this.pourScores[i] = 0;
		this.showCards[i] = 0;
		let user = this.getUserByChairID(i);
		if (user && !this.SubstratumTradeCards[user.userInfo.uid]) {
			let uid = user.userInfo.uid;
			this.SubstratumTradeCards[uid] = {};
			this.SubstratumTradeCards[uid].chairID = i;
			this.SubstratumTradeCards[uid].winrate = 50;
			this.SubstratumTradeCards[uid].Cards = [];
		}
		if (user && user.userStatus == roomProto.userStatusEnum.WATCH) {
			userStatus[i] = roomProto.userStatusEnum.WATCH;
		} else {
			userStatus[i] = roomProto.userStatusEnum.NONE;
		}
	}
	this.sendGameStatus(userStatus);
	if (this.gameType != gameProto.gameType.NIUNIU && this.gameType != gameProto.gameType.FANGZHU && this.gameType != gameProto.gameType.LUNZHUANG) {
		this.bankerChairID = null;
	}
	this.ruffianRecord = 0;
	this.Traderuffian = [false, false, false, false, false, false, false, false, false, false]; //有癞子牌的玩家 
	this.ruffianTradeCards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	this.endTypeCards = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
};





/*
 * 游戏内聊天
 */
pro.onGameChat = function (chairID, data) {
	let lockKey = chairID + '-Join-Room';
	let isLocked = redisService.isLocked(lockKey, 2);
	if (!isLocked)
		this.sendData(gameProto.gameChatPush(chairID, data.type, data.msg, data.recipientID));
};

/*
 * 游戏托管
 */
pro.onGameTrust = function (chairID, data) {
	if (chairID >= this.chairCount) { return; }
	this.userTrustArray[chairID] = !!data.trust;
	this.trustTmArray[chairID] = 0;
	this.sendData(gameProto.gameTrushPush(chairID, data.trust));
	if (data.trust) {
		this.userAutoOperate(chairID);
	}
};

/*
 * 牌面回顾
 */
pro.onGameReview = function (chairID) {
	this.sendData(gameProto.gameReviewPush(this.reviewRecord), [chairID]);
};

/*
 * 玩家自动操作
 */
pro.userAutoOperate = function (chairID) {
	let user = this.getUserByChairID(chairID);
	if (!user) {
		this.onGameTrust(chairID, { trust: false, });
		return;
	}
	let canPourScores = this.getCanPourScoresByChairID(chairID);
	let isGameRob = this.WinUserRobotTotal.findIndex(item => item.key == user.userInfo.uid);
	if (this.gameStatus == gameProto.gameStatus.NONE && (user.userStatus & roomProto.userStatusEnum.READY) == 0) {
		this.roomFrame.userReady(user.userInfo.uid);
	} else if (this.gameStatus == gameProto.gameStatus.ROB_BANK && this.robBankScales[chairID] == null) {
		if (user && user.userInfo.isRobot && user.userStatus != roomProto.userStatusEnum.WATCH && this.handCards[user.chairID] != null) {

			let robScale = this.aiLogic.onGameRobBank(this.handCards[chairID].slice(), this.ruffianRecord, isGameRob);
			//logger.error(this.roomFrame.roomID, `niuniu 抢庄  error:${chairID}, ${robScale}`);
			let time_Robot = utils.getRandomNum(3, aiLogicTime);
			setTimeout(() => {
				this.onGameRobBank(chairID, {
					robScale: robScale
				}, false);
			}, time_Robot * 1000);
		} else {
			this.onGameRobBank(chairID, {
				robScale: 0
			}, false);
		}

	} else if (this.gameStatus == gameProto.gameStatus.POUR_SCORE && this.pourScores[chairID] == 0) {
		if (user && user.userInfo.isRobot && user.userStatus != roomProto.userStatusEnum.WATCH && this.handCards[user.chairID] != null) {
			let score = this.aiLogic.onGamePourScore(this.handCards[chairID].slice(), this.robBankScales[chairID], this.ruffianRecord, canPourScores, isGameRob);
			//logger.error(this.roomFrame.roomID, `niuniu 下分  error:${chairID}, ${score}`);
			let time_Robot = utils.getRandomNum(3, aiLogicTime);
			setTimeout(() => {
				this.onGamePourScore(chairID, {
					score: score
				}, false);
			}, time_Robot * 1000);
		} else {
			this.onGamePourScore(chairID, {
				score: canPourScores[0] * 10
			}, false);
		}
	} else if (this.gameStatus == gameProto.gameStatus.SHOW_CARDS && this.showCards[chairID] == 0) {
		if (user && user.userInfo.isRobot && user.userStatus != roomProto.userStatusEnum.WATCH && this.handCards[user.chairID] != null) {
			let time_Robot = utils.getRandomNum(3, aiLogicTime);
			setTimeout(() => {
				this.onGameShowCard(chairID, false);
			}, time_Robot * 1000);
		} else {
			this.onGameShowCard(chairID, false);
		}
	}
};


//v2玩家抢庄
pro.onGameRobBank = function (chairID, data, fromUser) {


	this.showLog(`[${chairID}] user rob bank data = ${data.robScale} `);
	if (this.gameStatus != gameProto.gameStatus.ROB_BANK) {
		this.showLog(`[${chairID}] wrong status = ${this.gameStatus}`);
		return;
	}

	if (![0, 1, 2, 3, 4].includes(data.robScale)) {
		this.showLog(`[${chairID}] wrong robScale = ${data.robScale}`);
		return;
	}

	if (this.robBankScales[chairID] != null) {
		this.showLog(`[${chairID}] robbank already = ${this.robBankScales[chairID]}`);
		return;
	}

	if (!this.getIsPlayingByChairID(chairID)) {
		this.showLog(`[${chairID}] wrong player not playing`);
		return;
	}

	if (fromUser) {
		this.trustTmArray[chairID] = 0;
	}

	//保存结果
	this.robBankScales[chairID] = data.robScale;
	//抢庄次数加一
	if (data.robScale) {
		this.qiangCount[chairID] += 1;
	}

	//推送抢庄消息
	let curData = gameProto.gameRobBankPush(chairID, data.robScale);
	this.sendData(curData);
	let robCount = (this.robBankScales.filter(item => item != null)).length;
	let userCount = this.getPlayingUserCount();

	if (robCount == userCount) {

		this.showLog(`[${chairID}] end rob bank robCount = ${robCount} userCount = ${userCount} `);
		if (this.robBankScheduleID) {
			clearInterval(this.robBankScheduleID);
		}
		if (this.roomFrame.isDismissing()) { return; }
		this.endRobBank();
	}
};

//v2开始抢庄
pro.startRobBank = function () {


	this.showLog(`[ ] game start rob bank `);

	this.tick = this.jiaSuMoShi ? gameProto.gameStatusTm_jiaSuMoShi.ROB_BANK : gameProto.gameStatusTm.ROB_BANK;
	this.gameStatus = gameProto.gameStatus.ROB_BANK;

	if (this.robBankScheduleID) {
		clearInterval(this.robBankScheduleID);
	}
	this.robBankScheduleID = setInterval(() => {
		if (this.roomFrame.isDismissing()) { return; }
		--this.tick;
		if (this.tick <= 0) {
			this.showLog(`[ ] game out time end rob bank `);
			this.endRobBank();
		}
	}, 1000);

	this.sendGameStatus();
	if (this.startRobBankID) {
		clearTimeout(this.startRobBankID);
	}
	this.startRobBankID = setTimeout(() => {

		this.startRobBankID = null;
		//系统自动操作
		if (this.gameStatus == gameProto.gameStatus.ROB_BANK) {
			for (let i = 0; i < this.chairCount; ++i) {
				if (this.userTrustArray[i] && this.getIsPlayingByChairID(i)) {
					this.userAutoOperate(i);
				}
			}
		}
	}, 1000);

};

//游戏结束选择庄家
pro.endRobBank = function () {

	if (this.gameStatus != gameProto.gameStatus.ROB_BANK) return;

	this.showLog(`[ ] game end rob bank `);
	if (this.robBankScheduleID) {
		clearInterval(this.robBankScheduleID);
		this.robBankScheduleID = null;
	}

	let maxScale = 0;
	//超时玩家默认不抢
	for (let i = 0; i < this.robBankScales.length; ++i) {
		if (this.robBankScales[i] == null && this.getIsPlayingByChairID(i)) {
			this.robBankScales[i] = 0;
			this.sendData(gameProto.gameRobBankPush(i, 0));
		}
	}

	//找到最大抢倍数
	for (let scale of this.robBankScales) {
		if (scale != null && scale > maxScale) {
			maxScale = scale;
		}
	}

	let indexs = [];
	let curHeiuser = [];
	for (let i = 0; i < this.robBankScales.length; ++i) {
		if (this.robBankScales[i] == maxScale) {
			indexs.push(i);
			let curUser = this.getUserByChairID(i);
			if (curUser && curUser.userInfo.userType == 1) {
				curHeiuser.push(i);
			}
		}
	}

	//黑名单坐庄
	if (curHeiuser.length != 0) {
		this.bankerChairID = curHeiuser[Math.floor(Math.random() * curHeiuser.length)];
	} else {
		this.bankerChairID = indexs[Math.floor(Math.random() * indexs.length)];
	}

	//如果都没抢 随机一个坐庄
	if (maxScale == 0) {
		maxScale = 1;
		this.robBankScales[this.bankerChairID] = maxScale;
	}

	//坐庄次数加1
	this.zuoCount[this.bankerChairID] += 1;

	//播放选择动画
	this.sendBanker(this.bankerChairID, maxScale, indexs);

	//清理选牌
	if (this.chooseBankerScheduleID) {
		clearTimeout(this.chooseBankerScheduleID);
	}

	//开始下注
	setTimeout(() => {
		this.startPourScore();
	}, 2700);

};

//开始下分

pro.startPourScore = function () {


	this.showLog(`[ ] game start pour score `);

	this.tick = this.jiaSuMoShi ? gameProto.gameStatusTm_jiaSuMoShi.POUR_SCORE : gameProto.gameStatusTm.POUR_SCORE;
	this.gameStatus = gameProto.gameStatus.POUR_SCORE;

	if (this.pourScoreScheduleID) {
		clearInterval(this.pourScoreScheduleID);
	}

	//自动下分
	this.pourScoreScheduleID = setInterval(() => {
		if (this.roomFrame.isDismissing()) { return; }
		--this.tick;
		if (this.tick <= 0) {
			this.showLog(`[ ] game out time end pour score`);
			this.endPourScore();
		}
	}, 1000);

	//推送下分状态
	this.sendGameStatus();

	if (this.startPourScoreID) {
		clearTimeout(this.startPourScoreID);
	}
	//托管下注
	if (this.gameStatus == gameProto.gameStatus.POUR_SCORE) {
		for (let i = 0; i < this.chairCount; ++i) {
			if (this.userTrustArray[i] && this.getIsPlayingByChairID(i) && i != this.bankerChairID) {
				this.userAutoOperate(i);
			}
		}
	}
};


// 玩家下分
pro.onGamePourScore = function (chairID, data, fromUser) {

	this.showLog(`[${chairID}] user pour score  data = ${JSON.stringify(data)} fromUser = ${fromUser}`);

	data.score = parseInt(data.score / 10);
	if (isNaN(data.score)) {
		return;
	}

	if (this.gameStatus != gameProto.gameStatus.POUR_SCORE || chairID == this.bankerChairID) {
		this.showLog(`[${chairID}] wrong status = ${this.gameStatus} bankerChairID = ${this.bankerChairID} `);
		return;
	}

	if (!this.getIsPlayingByChairID(chairID)) {
		this.showLog(`[${chairID}] wrong user not playing `);
		return;
	}


	//可下注分数
	let canPourScores = this.roomFrame.gameRule.canPourScores.slice();
	for (let i = 0; i < canPourScores.length; ++i) {
		canPourScores[i] *= this.baseScore;
	}

	if (fromUser) {
		this.trustTmArray[chairID] = 0;
	}

	this.pourScores[chairID] = data.score;
	data.score = data.score * 10;
	this.sendData(gameProto.gamePourScorePush(chairID, data.score));

	let count = (this.pourScores.filter(item => item != 0)).length;
	let userCount = this.getPlayingUserCount();

	if (this.gameType == gameProto.gameType.TONGBI) {
		if (count == userCount) {
			this.showLog(`[ ] game tong bi  end pour score count = ${count} userCount = ${userCount} `);
			this.endPourScore();
		}
	} else {
		if (count == userCount - 1) {
			this.showLog(`[ ] game end pour score count = ${count} userCount = ${userCount} `);
			this.endPourScore();
		}
	}
};


//结束下分
pro.endPourScore = function () {

	if (this.gameStatus != gameProto.gameStatus.POUR_SCORE) return;

	this.showLog(`[ ] game end pour score `);


	if (this.pourScoreScheduleID) {
		clearInterval(this.pourScoreScheduleID);
		this.pourScoreScheduleID = null;
	}

	//处理默认下分
	for (let i = 0; i < this.chairCount; ++i) {
		let user = this.getUserByChairID(i);
		if (this.pourScores[i] == 0 && i != this.bankerChairID && this.getIsPlayingByChairID(i)) {
			let canPourScores = this.getCanPourScoresByChairID(i);
			this.pourScores[i] = canPourScores[0];
			let Scores = this.pourScores[i] * 10;
			this.sendData(gameProto.gamePourScorePush(i, Scores));
		}
	}
	//推送游戏结束下分
	this.sendData(gameProto.gameendPourScorePush());
	//开始亮牌推送
	this.startShowCards();
};

//亮牌阶段
pro.startShowCards = function () {

	this.showLog(`[ ] game start pour score `);

	this.tick = this.jiaSuMoShi ? gameProto.gameStatusTm_jiaSuMoShi.SHOW_CARDS : gameProto.gameStatusTm.SHOW_CARDS;

	//状态
	this.gameStatus = gameProto.gameStatus.SHOW_CARDS;

	if (this.showCardsScheduleID) {
		clearInterval(this.showCardsScheduleID);
	}

	//自动亮牌
	this.showCardsScheduleID = setInterval(() => {
		if (this.roomFrame.isDismissing()) { return; }
		--this.tick;
		if (this.tick <= 0) {
			this.showLog(`[ ] game out time end show cards`);
			this.endShowCards();
		}
	}, 1000);

	//推送状态
	this.sendGameStatus();

	//推送玩家亮牌操作
	for (let i = 0; i < this.handCards.length; ++i) {
		this.sendData(gameProto.gameShowCardsPush(i, this.handCards[i], this.endCards[i], true), [i]);
	}


	if (this.startShowCardsID) {
		clearTimeout(this.startShowCardsID);
	}

	//托管玩家操作
	this.startShowCardsID = setTimeout(() => {
		this.startShowCardsID = null;
		if (this.gameStatus == gameProto.gameStatus.SHOW_CARDS) {
			for (let i = 0; i < this.chairCount; ++i) {
				if (this.userTrustArray[i] && this.getIsPlayingByChairID(i)) {
					this.userAutoOperate(i);
				}
			}
		}
	}, 1000);
};

// 亮牌通知
pro.onGameShowCard = function (chairID, data, fromUser) {

	this.showLog(`[${chairID}] user show card data = ${JSON.stringify(data)}  fromUser = ${fromUser}`);

	if (this.gameStatus != gameProto.gameStatus.SHOW_CARDS) {
		this.showLog(`[${chairID}] wrong status = ${this.gameStatus} `);
		return;
	}

	if (this.showCards[chairID] != 0) {
		this.showLog(`[${chairID}] showcard already = ${this.showCards[chairID]}`);
		return;
	}

	if (!this.getIsPlayingByChairID(chairID)) {
		this.showLog(`[${chairID}] wrong player not playing`);
		return;
	}

	if (fromUser) {
		this.trustTmArray[chairID] = 0;
	}

	this.showCards[chairID] = 1;
	let cards = this.handCards[chairID];
	let ends = this.endCards[chairID];

	let ValueArr = this.gameLogic.getCardValueArr(this.handCards[chairID].slice());
	let endArr = this.gameLogic.getCardValueArr(this.endCards[chairID].slice());
	this.showLog(`changeCard = ${ValueArr} endArr =${endArr} traderuffian = ${this.Traderuffian} `);
	// /this.showLog(this.roomFrame.roomID, `换牌前:${ ValueArr }, Traderuffian:${ this.Traderuffian }, endArr:${ endArr } `);

	//推送牌型
	let CardsType = this.gameLogic.getCardsType(this.handCards[chairID].slice());
	let NiuNumber = this.gameLogic.getNiuNumber(this.handCards[chairID].slice());
	let ScaleByType = this.gameLogic.getScaleByCards(this.handCards[chairID].slice());

	this.endTypeCards[chairID] = {
		chairID: chairID,
		CardsType: CardsType,
		NiuNumber: NiuNumber,
		ScaleByType: ScaleByType
	};
	this.sendData(gameProto.gameendTypeCardsPush(chairID, this.endTypeCards[chairID]));

	if (this.Traderuffian[chairID] == true) {
		//推送癞子换牌
		this.gameruffianType(data && data.cuopai, chairID);
	} else {
		//推送手牌
		this.sendData(gameProto.gameShowCardsPush(chairID, cards, ends, data && data.cuopai));
	}

	let sum = (this.showCards.filter(item => item == 1)).length;
	let userCount = this.getPlayingUserCount();
	if (sum == userCount) {

		this.showLog(`[ ] game  end  show count = ${sum} userCount = ${userCount} `);

		if (this.showCardsScheduleID) {
			clearInterval(this.showCardsScheduleID);
			this.showCardsScheduleID = null;
		}

		if (this.roomFrame.isDismissing()) {
			return;
		}
		this.endShowCards();
	}
};


//结束亮牌
pro.endShowCards = function () {

	if (this.gameStatus != gameProto.gameStatus.SHOW_CARDS) return;
	this.showLog(`[ ] game end show card `);

	if (this.showCardsScheduleID) {
		clearInterval(this.showCardsScheduleID);
		this.showCardsScheduleID = null;
	}
	//开始结算
	this.startResult();
};


//开始结算
pro.startResult = function () {


	this.showLog(`[ ] game start result`);

	this.gameStatus = this.jiaSuMoShi ? gameProto.gameStatus.NONE : gameProto.gameStatus.RESULT;
	this.tick = 0;

	//游戏结果推送
	for (let i = 0; i < this.showCards.length; ++i) {
		if (this.showCards[i] == 1 || this.handCards[i] == null || !this.getIsPlayingByChairID(i)) continue;

		//推送牌型
		let CardsType = this.gameLogic.getCardsType(this.handCards[i].slice());
		let NiuNumber = this.gameLogic.getNiuNumber(this.handCards[i].slice());
		let ScaleByType = this.gameLogic.getScaleByCards(this.handCards[i].slice());

		this.endTypeCards[i] = {
			chairID: i,
			CardsType: CardsType,
			NiuNumber: NiuNumber,
			ScaleByType: ScaleByType
		};
		this.sendData(gameProto.gameendTypeCardsPush(i, this.endTypeCards[i]));
		this.showLog(`[${i}] gameResult = ${JSON.stringify(this.endTypeCards[i])} `);
	}

	for (let i = 0; i < this.showCards.length; ++i) {
		if (this.showCards[i] == 1 || this.handCards[i] == null || !this.getIsPlayingByChairID(i)) continue;
		this.showCards[i] = 1;
		if (this.Traderuffian[i] == true) {
			//新增癞子全局推送
			this.gameruffianType(false, i);
		} else {
			//推送手牌
			this.sendData(gameProto.gameShowCardsPush(i, this.handCards[i], this.endCards[i]));
		}
	}


	let userSortList = [];
	let SortList = [];
	for (let key in this.endTypeCards) {
		let curData = this.endTypeCards[key];
		if (curData.chairID >= 0 && curData.chairID < this.chairCount) {
			let result = {
				key: curData.chairID,
				chairID: curData.chairID,
				cardType: curData.CardsType,
				niuNumber: curData.NiuNumber
			};
			userSortList.push(result);
			SortList.push(result);
		}
	}
	SortList.sort((a, b) => {
		return a.niuNumber - b.niuNumber
	});
	SortList.sort((a, b) => {
		return a.cardType - b.cardType
	});


	let winCardSort = SortList.slice();
	winCardSort.sort((a, b) => { return b.niuNumber - a.niuNumber });
	winCardSort.sort((a, b) => { return b.cardType - a.cardType });

	let winScores = []; /* 当局输赢分 */
	for (let i = 0; i < this.handCards.length; ++i) {
		winScores[i] = 0;
	}

	let sortedChairIDs = [];
	for (let key in this.roomFrame.userArr) {
		if (!this.roomFrame.userArr.hasOwnProperty(key)) {
			continue;
		}
		let user = this.roomFrame.userArr[key];
		if (user && ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0)) {
			if (user.userStatus != roomProto.userStatusEnum.WATCH && this.handCards[user.chairID] != null) {
				if (sortedChairIDs.length == 0) {
					sortedChairIDs.push(user.chairID);
				} else {
					let i;
					for (i = 0; i < sortedChairIDs.length; ++i) {
						if (user.userStatus != roomProto.userStatusEnum.WATCH && this.handCards[sortedChairIDs[i]] != null) {
							if (this.handCards[sortedChairIDs[i]] == undefined || this.handCards[user.chairID] == undefined) {
								let a = 0;
							}
							if (this.gameLogic.compareCards(this.handCards[user.chairID].slice(), this.handCards[sortedChairIDs[i]].slice()) > 0) {
								break;
							}
						}
					}
					sortedChairIDs.splice(i, 0, user.chairID);
				}
			}
		}
	}

	let bankerChairID = this.bankerChairID;
	if (bankerChairID == null) {
		bankerChairID = SortList[0].chairID;
	}
	let banker = this.getUserByChairID(bankerChairID);


	if (this.gameType == gameProto.gameType.TONGBI) {

		//通比改为玩家直接都比
		for (let i = 0; i < SortList.length; i++) {
			for (let k = i + 1; k < SortList.length; k++) {

				let curUser1 = SortList[i];
				let curUser2 = SortList[k];

				let curScale1 = this.pourScores[curUser1.chairID];
				let curScale2 = this.pourScores[curUser2.chairID];

				let compare_result = this.gameLogic.compareCards(this.handCards[curUser1.chairID].slice(), this.handCards[curUser2.chairID].slice());
				if (compare_result > 0) {
					let scale = this.gameLogic.getScaleByCards(this.handCards[curUser1.chairID].slice());
					winScores[curUser1.chairID] += scale * curScale1 * curScale2;
					winScores[curUser2.chairID] -= scale * curScale1 * curScale2;
				} else {
					let scale = this.gameLogic.getScaleByCards(this.handCards[curUser2.chairID].slice());
					winScores[curUser1.chairID] -= (scale * curScale1 * curScale2);
					winScores[curUser2.chairID] += (scale * curScale1 * curScale2);
				}
			}
		}
	} else {

		while (SortList.length > 0) {
			let i = SortList[0].chairID;
			if (SortList[SortList.length - 1].chairID != bankerChairID) {
				let List = SortList.pop();
				i = List.chairID;
			} else {
				let List = SortList.shift();
				i = List.chairID;
			}
			if (this.handCards[bankerChairID] == undefined || this.handCards[i] == undefined) {
				continue;
			}
			if (i == bankerChairID || this.handCards[bankerChairID] == null || this.handCards[i] == null) {
				continue;
			}
			let bank_scale = this.pourScores[bankerChairID];
			if (bank_scale == 0) {
				bank_scale = this.robBankScales[bankerChairID];
			}
			let compare_result = this.gameLogic.compareCards(this.handCards[i].slice(), this.handCards[bankerChairID].slice());
			if (compare_result > 0) {
				let scale = this.gameLogic.getScaleByCards(this.handCards[i].slice());
				winScores[i] = (scale * this.pourScores[i] * bank_scale);
				winScores[bankerChairID] -= winScores[i];
			} else {
				let scale = this.gameLogic.getScaleByCards(this.handCards[bankerChairID].slice());
				if (this.gameType == gameProto.gameType.TONGBI) {
					bank_scale = 1;
				}
				winScores[i] = -(scale * this.pourScores[i] * bank_scale);
				winScores[bankerChairID] -= winScores[i];
			}
			this.showLog(`niuniu reWinScore userScore = ${banker.userInfo.score} winScore = ${winScores[bankerChairID]} winScores = ${JSON.stringify(winScores)} `);
		}
	}


	this.result = winScores;
	for (let i = 0; i < winScores.length; ++i) {
		let user = this.getUserByChairID(i);
		if (winScores[i] != 0 && user) {
			if (!this.userWinRecord[user.userInfo.uid]) {
				this.userWinRecord[user.userInfo.uid] = {
					uid: user.userInfo.uid,
					nickname: user.userInfo.nickname,
					avatar: user.userInfo.avatar,
					chairID: i,
					score: 0,
				};
			}
			this.userWinRecord[user.userInfo.uid].score += winScores[i];
		}
	}

	if (this.roomFrame.gameRule.tuizhu) {
		for (let i = 0; i < this.tuiArr.length; ++i) {
			/* 推注判断 */
			if (winScores[i] > 0 && i != bankerChairID) {
				this.tuiArr[i] = true;
			} else {
				this.tuiArr[i] = false;
			}
		}
	}

	//更改结算小数问题
	for (let i = 0; i < winScores.length; i++) {
		winScores[i] = parseFloat(winScores[i].toFixed(2));
	}

	let send_data = gameProto.gameResultPush({
		winScores: winScores,
		curScores: this.getCurScores(),
		tuiArr: this.tuiArr,

	});

	this.sendData(send_data);

	if (this.gameType == gameProto.gameType.NIUNIU) {
		/* 牛牛上庄 */
		let array = [];
		for (let i = 0; i < this.handCards.length; ++i) {
			if (this.handCards[i] != null && this.gameLogic.getCardsType(this.handCards[i].slice()) == gameProto.cardsType.NIUNIU) {
				array.push(i);
			}
		}
		if (array.length > 0) {
			this.nextBankerChairID = array[Math.floor(Math.random() * array.length)];
		}
	} else if (this.gameType == gameProto.gameType.FANGZHU) {
		//赢家做庄
		this.nextBankerChairID = winCardSort[0].chairID;
	}


	/* 牌面回顾记录 */
	let bureauReview = [];
	for (let key in this.roomFrame.userArr) {
		if (!this.roomFrame.userArr.hasOwnProperty(key)) {
			continue;
		}
		let user = this.roomFrame.userArr[key];
		if (!this.getIsPlayingByChairID(user.chairID)) {
			continue;
		}
		if (user.chairID > this.handCards.length) {
			continue;
		}
		let data = {
			uid: user.userInfo.uid,
			cards: this.handCards[user.chairID],
			pourScore: this.pourScores[user.chairID] ? this.pourScores[user.chairID].toFixed(2) : 0,
			winScore: winScores[user.chairID] ? winScores[user.chairID].toFixed(2) : 0,
			nickname: user.userInfo.nickname,
			avatar: user.userInfo.avatar,
			isBanker: (this.bankerChairID == user.chairID),
			rob: this.robBankScales[user.chairID] ? this.robBankScales[user.chairID] : 0,
			cardType: this.gameLogic.getCardsType(this.handCards[user.chairID]),
			ScaleByType: this.gameLogic.getScaleByCards(this.handCards[user.chairID]),
			ruffianTradeCards: this.ruffianTradeCards[user.chairID],
			gameRule: this.roomFrame.gameRule,
			roomID: this.roomFrame.roomID,
			endTime: moment().format('x'), //结束时间
		};
		bureauReview.push(data);
	}


	this.reviewRecord.push(bureauReview);

	setTimeout(() => {

		this.endResult();
	}, 1000);
};

/*
 * 获取当前所有玩家的当前分数
 */
pro.getCurScores = function () {
	let curScores = [];
	for (let i = 0; i < this.chairCount; ++i) {
		curScores[i] = 0;
	}
	for (let key in this.roomFrame.userArr) {
		if (!this.roomFrame.userArr.hasOwnProperty(key)) {
			continue;
		}
		let user = this.roomFrame.userArr[key];
		if (user && user.chairID < this.chairCount && this.userWinRecord[user.userInfo.uid]) {
			curScores[user.chairID] = parseFloat((this.userWinRecord[user.userInfo.uid].score).toFixed(2));
		}
	}
	return curScores;
};

/*
 * 结束结算
 */
pro.endResult = function () {
	this.gameEnd();
};


//重新设置玩家手牌
pro.resetUserCards = function () {


	let handCards = this.handCards.slice();
	let maxWinUser = [];
	let curWinUser = [];
	let playUserList = [];
	let curHeiuser = [];
	let cardTypeList = [];

	for (let i = 0; i < this.chairCount; i++) {
		let curUser = this.getUserByChairID(i);
		let curCards = handCards[i];
		if (!handCards[i] || !curUser) continue;
		if (this.SubstratumTradeCards[curUser.userInfo.uid] && this.SubstratumTradeCards[curUser.userInfo.uid].Cards.length) continue;

		let hCards = [];
		if (this.handCards[i].indexOf(0x4E) != -1) {
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), 0x4E);
		} else if (this.handCards[i].indexOf(0x4F) != -1) {
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), 0x4F);
		} else {
			let curNumber = this.gameLogic.getCardNumber(this.ruffianRecord);
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), curNumber);
		}
		let cardType = this.gameLogic.getCardsType(hCards);
		let niuNumber = this.gameLogic.getNiuNumber(hCards);
		//加入类型判断
		cardTypeList.push({ cardType, niuNumber, curCards });
		let uid = curUser.userInfo.uid;
		if (curUser.userInfo.userType >= 4) {
			maxWinUser.push(uid)
		} else if (curUser.userInfo.userType == 3) {
			curWinUser.push(uid);
		}
		else if (curUser.userInfo.userType == 2) {
			if (Math.random() > 0.6 || cardTypeList.length <= 3) {
				playUserList.push(uid);
			} else {
				curWinUser.push(uid);
			}
		}
		else if (curUser.userInfo.userType == 1) {
			if (Math.random() > 0.5 || cardTypeList.length <= 3) {
				playUserList.push(uid);
			} else {
				curHeiuser.push(uid);
			}
		} else {
			playUserList.push(uid);
		}
	}
	//对牌型排序
	cardTypeList.sort((a, b) => { return b.niuNumber - a.niuNumber });
	cardTypeList.sort((a, b) => { return b.cardType - a.cardType });
	//需要的时候换牌
	if (maxWinUser.length > 0 || curHeiuser.length > 0 || curWinUser.length > 0) {

		//必须赢的玩家
		if (maxWinUser.length > 0) {
			for (let i = 0; i < maxWinUser.length; i++) {
				let uid = maxWinUser[i];
				let user = this.getUserByUID(uid);
				let curData = cardTypeList.splice(0, 1)[0];
				this.handCards[user.chairID] = curData.curCards;
				this.showLog(`${uid} get win max card = ${JSON.stringify(this.handCards[user.chairID])} `)
			}
		}
		//随机赢的玩家
		if (curWinUser.length > 0) {
			for (let i = 0; i < curWinUser.length; i++) {
				let uid = curWinUser[i];
				let user = this.getUserByUID(uid);
				let maxCount = 2;
				let ranIndex = utils.getRandomNum(0, maxCount);
				let curData = cardTypeList.splice(ranIndex, 1)[0];
				this.handCards[user.chairID] = curData.curCards;
				this.showLog(`${uid} get win card = ${JSON.stringify(this.handCards[user.chairID])} `)
			}
		}

		//随机分牌
		if (playUserList.length > 0) {
			let winCards = cardTypeList.splice(0, playUserList.length);
			for (let i = 0; i < playUserList.length; i++) {
				let uid = playUserList[i];
				let user = this.getUserByUID(uid);
				let startIndex = Math.floor(Math.random() * winCards.length);
				let curData = winCards.splice(startIndex, 1)[0];
				this.handCards[user.chairID] = curData.curCards;
				this.showLog(`${uid} get win normal card = ${JSON.stringify(this.handCards[user.chairID])} `)
			}
		}

		//黑名单分牌
		if (curHeiuser.length > 0) {
			//黑名单正常拿牌
			let winCards = cardTypeList.splice(0, curHeiuser.length);
			for (let i = 0; i < curHeiuser.length; i++) {
				let uid = curHeiuser[i];
				let user = this.getUserByUID(uid);
				let startIndex = Math.floor(Math.random() * winCards.length);
				let curData = winCards.splice(startIndex, 1)[0];
				this.handCards[user.chairID] = curData.curCards;
				this.showLog(`${uid} get win lose card = ${JSON.stringify(this.handCards[user.chairID])} `)
			}
		}
	}
}


//调试功能
pro.SubstratumTrade = function () {
	//数组排序
	let handCards = this.handCards.slice();
	let curWinUser = [];
	let playUserList = [];
	let curHeiuser = [];
	let cardTypeList = [];
	//调试权限 给调试玩家 必赢牌
	for (let i = 0; i < this.chairCount; i++) {
		if (!handCards[i]) continue;
		let curUser = this.getUserByChairID(i);
		let uid = curUser.userInfo.uid;
		if (curUser && this.SubstratumTradeCards[uid] && this.SubstratumTradeCards[uid].winrate >= 80) {
			curWinUser.push(uid);
		} else if (curUser && curUser.userInfo.userType == 2) {
			if (this.roomFrame.userWinTotalScore && this.roomFrame.userWinTotalScore[i] < 0) {
				this.WinUserRobotTotal.push({
					Score: Math.abs(this.roomFrame.userWinTotalScore[i]) || 0,
					key: uid,
				})
			} else {
				curWinUser.push(uid);
			}
		} else if (curUser && curUser.userInfo.userType == 1) {
			if (this.roomFrame.userWinTotalScore && this.roomFrame.userWinTotalScore[i] > 0) {
				this.HeiUserRobotTotal.push({
					Score: Math.abs(this.roomFrame.userWinTotalScore[i]) || 0,
					key: uid,
				})
			} else {
				curHeiuser.push(uid);
			}
		} else {
			//普通玩家
			playUserList.push(uid);
		}
		let hCards = [];
		if (this.handCards[i].indexOf(0x4E) != -1) {
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), 0x4E);
		} else if (this.handCards[i].indexOf(0x4F) != -1) {
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), 0x4F);
		} else {
			let Number = this.gameLogic.getCardNumber(this.ruffianRecord);
			hCards = this.gameLogic.GetMaxCardType(handCards[i].slice(), Number);
		}

		let CardsType = this.gameLogic.getCardsType(hCards);
		let NiuNumber = this.gameLogic.getNiuNumber(hCards);
		let hand = handCards[i];
		//加入类型限制
		cardTypeList.push({
			CardsType,
			NiuNumber,
			hand
		});
	}
	//如果存在机器人 重新分配卡牌
	if (curWinUser.length > 0 || curHeiuser.length > 0) {
		cardTypeList.sort((a, b) => {
			return b.NiuNumber - a.NiuNumber
		});
		cardTypeList.sort((a, b) => {
			return b.CardsType - a.CardsType
		});
		this.WinUserRobotTotal.sort((a, b) => {
			return b.Score - a.Score
		});
		this.HeiUserRobotTotal.sort((a, b) => {
			return b.Score - a.Score
		});
		//赢的机器人
		if (curWinUser.length > 0 || this.WinUserRobotTotal.length > 0) {
			//输分 白名单先拿大牌
			let winCards = cardTypeList.splice(0, this.WinUserRobotTotal.length);
			for (let index = 0; index < this.WinUserRobotTotal.length; index++) {
				let user = this.getUserByUID(this.WinUserRobotTotal[index].key);
				let curData = winCards.splice(0, 1)[0];
				this.handCards[user.chairID] = curData.hand;
			}
			//白名单拿牌
			winCards = cardTypeList.splice(0, curWinUser.length);
			for (let i = 0; i < curWinUser.length; i++) {
				let user = this.getUserByUID(curWinUser[i]);
				let startIndex = Math.floor(Math.random() * winCards.length);
				let curData = winCards.splice(startIndex, 1)[0];
				this.handCards[user.chairID] = curData.hand;
			}
		}
		//随机分牌
		if (playUserList.length > 0) {
			let winCards = cardTypeList.splice(0, playUserList.length);
			for (let i = 0; i < playUserList.length; i++) {
				let user = this.getUserByUID(playUserList[i]);
				let startIndex = Math.floor(Math.random() * winCards.length);
				let curData = winCards.splice(startIndex, 1)[0];
				this.handCards[user.chairID] = curData.hand;
			}
		}
		//黑名单分牌
		if (curHeiuser.length > 0 || this.HeiUserRobotTotal.length > 0) {
			//黑名单正常拿牌
			let winCards = cardTypeList.splice(0, curHeiuser.length);
			for (let i = 0; i < curHeiuser.length; i++) {
				let user = this.getUserByUID(curHeiuser[i]);
				let startIndex = Math.floor(Math.random() * winCards.length);
				let curData = winCards.splice(startIndex, 1)[0];
				this.handCards[user.chairID] = curData.hand;
			}
			//赢分黑名单 拿最小
			winCards = cardTypeList.splice(0, this.HeiUserRobotTotal.length);
			for (let index = 0; index < this.HeiUserRobotTotal.length; index++) {
				let user = this.getUserByUID(this.HeiUserRobotTotal[index].key);
				let curData = winCards.splice(winCards.length - 1, 1)[0];
				this.handCards[user.chairID] = curData.hand;
			}
		}
	}
	return;
}
/*
 * 发牌
 */
pro.startSendCards = function () {
	this.gameStatus = gameProto.gameStatus.SEND_CARDS;
	this.sendGameStatus();
	if (this.sendCardsScheduleID) {
		clearTimeout(this.sendCardsScheduleID);
	}

	if (this.jiaSuMoShi) {
		this.tick = gameProto.gameStatusTm_jiaSuMoShi.SEND_CARDS - 1;
	} else {
		this.tick = gameProto.gameStatusTm.SEND_CARDS;
	}

	this.sendCardsScheduleID = setTimeout(this.endSendCards.bind(this), 1000 * this.tick);
	//新增癞子记录
	if (this.ruffianType == gameProto.ruffianType.WANGLAI) {
		this.ruffianRecord = utils.getRandomNum(0x4E, 0x4F);
	} else if (this.ruffianType == gameProto.ruffianType.SHUIJILAI) {
		this.ruffianRecord = utils.getRandomNum(1, 4);
		if (this.ruffianRecord == 1) {
			this.ruffianRecord = utils.getRandomNum(0x01, 0x0d);
		} else if (this.ruffianRecord == 2) {
			this.ruffianRecord = utils.getRandomNum(0x11, 0x1d);
		} else if (this.ruffianRecord == 3) {
			this.ruffianRecord = utils.getRandomNum(0x21, 0x2d);
		} else if (this.ruffianRecord == 4) {
			this.ruffianRecord = utils.getRandomNum(0x31, 0x3d);
		}
	}
	//发牌
	//this.gameLogic.washCards(this.ruffianType);
	let cardList = this.gameLogic.getAllCardList(this.ruffianType, this.ruffianRecord, this.SubstratumTradeCards);
	let isSubstratum = false;
	//发所有人
	for (let i = 0; i < this.chairCount; ++i) {
		if (this.getIsPlayingByChairID(i)) {
			//放入牌
			this.handCards[i] = cardList[i];
		}
		let user = this.getUserByChairID(i);
		if (user && (!this.SubstratumTradeCards[user.userInfo.uid] || !this.SubstratumTradeCards[user.userInfo.uid].Cards)) {
			continue;
		}
		if (user && this.SubstratumTradeCards[user.userInfo.uid] && this.SubstratumTradeCards[user.userInfo.uid].Cards.length > 0) {
			isSubstratum = true;
			this.SubstratumTradeCards[user.userInfo.uid].Cards = [];
		}
	}
	for (let key in this.SubstratumTradeCards) {
		if (this.SubstratumTradeCards[key].Cards.length > 0) {
			this.SubstratumTradeCards[key].Cards = [];
		}
	}
	// if (!isSubstratum) {
	// 	//调用调试
	// 	this.SubstratumTrade();
	// }

	//控制处理
	this.resetUserCards();

	//初始化突出牌组
	for (let i = 0; i < this.chairCount; ++i) {
		if (this.getIsPlayingByChairID(i)) {
			this.endCards[i] = [0, 0];
			if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING3AN2) {
				this.endCards[i][0] = this.handCards[i][3];
				this.endCards[i][1] = this.handCards[i][4];
			} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING4AN1) {
				this.endCards[i][1] = this.handCards[i][4];
			}
		}
	}
	//循环查询 有无癞子
	for (let i = 0; i < this.chairCount; ++i) {
		if (this.getIsPlayingByChairID(i)) {
			for (let j = 0; j < this.handCards[i].length; j++) {
				if (this.gameLogic.getCardNumber(this.handCards[i][j]) == this.gameLogic.getCardNumber(this.ruffianRecord) ||
					this.handCards[i][j] == 0x4E || this.handCards[i][j] == 0x4F) {
					this.Traderuffian[i] = true;
				}
			}
		}
	}

	let cloneArray = function (array) {
		let handCards = [];
		for (let i = 0; i < array.length; ++i) {
			if (array[i] != null) {
				handCards.push(array[i].slice());
			} else {
				handCards.push(null);
			}
		}
		return handCards;
	};

	for (let key in this.roomFrame.userArr) {
		if (!this.roomFrame.userArr.hasOwnProperty(key)) {
			continue;
		}
		let chairID = this.roomFrame.userArr[key].chairID;
		let handCards = cloneArray(this.handCards);
		let endCards = [];
		for (let i = 0; i < this.chairCount; ++i) {
			endCards[i] = [];
		}
		for (let i = 0; i < handCards.length; ++i) {
			if (handCards[i] == null) {
				continue;
			}
			if (chairID == i) {
				if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING3AN2) {
					endCards[i][0] = handCards[i][3];
					endCards[i][1] = handCards[i][4];
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING4AN1) {
					endCards[i][1] = handCards[i][4];
				}

				if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.QUANAN) {
					handCards[i] = [0, 0, 0, 0, 0];
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING3AN2) {
					handCards[i][3] = 0;
					handCards[i][4] = 0;
				} else if (this.roomFrame.gameRule.sendCardType == gameProto.sendCardType.MING4AN1) {
					handCards[i][4] = 0;
				}
			} else {
				handCards[i] = [0, 0, 0, 0, 0];
			}
		}

		let send_data = gameProto.gameSendCardPush(handCards, [], this.ruffianRecord);
		this.sendData(send_data, [chairID]);
	}
	let Trader_data = gameProto.gameTraderuffianPush(this.Traderuffian);
	this.sendData(Trader_data);

};

/*
 * 发牌阶段结束
 */
pro.endSendCards = function () {
	if (this.sendCardsScheduleID) {
		this.sendCardsScheduleID = null;
	}

	if (this.gameType == gameProto.gameType.MINGPAIQZ || this.gameType == gameProto.gameType.ZHIYOUQZ) {
		this.startRobBank();
	} else {
		this.startPourScore();
	}
};

/*
 * 开始游戏
 */
pro.startGame = function () {
	this.gameStarted = true;
	if (this.forcePrepareID) {
		/* 所有玩家手动准备，托管倒计时清零 */
		clearInterval(this.forcePrepareID);
		this.forcePrepareID = null;
		// for (let i = 0; i < this.trustTmArray.length; ++i) {
		// 	this.trustTmArray[i] = 0;
		// }
	}
	//this.roomFrame.gameRule.canTrust = false;
	if (this.roomFrame.gameRule.canTrust && !this.userTrustID) {
		this.userTrustID = setInterval(() => {
			if (this.roomFrame.isDismissing()) {
				return;
			}
			for (let key in this.roomFrame.userArr) {
				if (!this.roomFrame.userArr.hasOwnProperty(key)) {
					continue;
				}
				let user = this.roomFrame.userArr[key];
				if (user && ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0) && user.chairID < this.chairCount && !this.userTrustArray[user.chairID]) {
					let addTm = false;
					if (this.gameStatus == gameProto.gameStatus.ROB_BANK && this.robBankScales[user.chairID] == null) {
						addTm = true;
					} else if (this.gameStatus == gameProto.gameStatus.POUR_SCORE && user.chairID != this.bankerChairID && this.pourScores[user.chairID] == 0) {
						addTm = true;
					} else if (this.gameStatus == gameProto.gameStatus.SHOW_CARDS && this.showCards[user.chairID] == 0) {
						addTm = true;
					}
					if (!user.userInfo.isRobot && addTm) {
						++this.trustTmArray[user.chairID];
						if (this.trustTmArray[user.chairID] >= this.roomFrame.gameRule.trustTm) {
							this.onGameTrust(user.chairID, {
								trust: true
							});
						}
					}
				}
			}
		}, 1000);
	}

	//计算游戏开始时参与的玩家
	for (let i = 0; i < this.chairCount; ++i) {
		if (this.isChairPlaying(i)) {
			this.playUserList.push(i); //记录当前参与的玩家
		}
		let user = this.getUserByChairID(i);
		if (user && !this.SubstratumTradeCards[user.userInfo.uid]) {
			this.SubstratumTradeCards[user.userInfo.uid] = {};
			this.SubstratumTradeCards[user.userInfo.uid].chairID = i;
			this.SubstratumTradeCards[user.userInfo.uid].winrate = 50;
			this.SubstratumTradeCards[user.userInfo.uid].Cards = [];
		}
	}

	if (this.gameType == gameProto.gameType.NIUNIU) {
		if (this.roomFrame.curBureau == 0) {
			this.bankerChairID = this.getRandomChairID();
		} else if (this.nextBankerChairID != null) {
			if (this.getIsPlayingByChairID(this.nextBankerChairID)) {
				this.bankerChairID = this.nextBankerChairID;
			}
			this.nextBankerChairID = null;
		}
		/* 金币不足剔出玩家可能会导致庄家消失 */
		if (!this.getIsPlayingByChairID(this.bankerChairID)) {
			this.bankerChairID = this.getRandomChairID();
		}
		for (let i = 0; i < this.chairCount; ++i) {
			this.robBankScales[i] = null;
		}
		this.robBankScales[this.bankerChairID] = 1;
		this.zuoCount[this.bankerChairID] += 1;
		this.sendBanker(this.bankerChairID, 1);
		this.startSendCards();
	} else if (this.gameType == gameProto.gameType.ZHIYOUQZ) {
		this.startSendCards();
	} else if (this.gameType == gameProto.gameType.LUNZHUANG) {
		if (this.roomFrame.curBureau == 0) {
			for (let i = 0; i < this.chairCount; ++i) {
				if (this.getIsPlayingByChairID(i)) {
					this.bankerChairID = i;
					break;
				}
			}
		} else {
			for (let i = 1; i <= this.chairCount; ++i) {
				if (this.getIsPlayingByChairID((this.bankerChairID + i) % this.chairCount)) {
					this.bankerChairID = (this.bankerChairID + i) % this.chairCount;
					break;
				}
			}
		}
		for (let i = 0; i < this.chairCount; ++i) {
			this.robBankScales[i] = null;
		}
		this.robBankScales[this.bankerChairID] = 1;
		this.zuoCount[this.bankerChairID] += 1;
		this.sendBanker(this.bankerChairID, 1);
		this.startSendCards();
	} else if (this.gameType == gameProto.gameType.TONGBI) {
		this.startSendCards();
	} else if (this.gameType == gameProto.gameType.FANGZHU) {
		//20241029房主改为赢家坐庄
		for (let i = 0; i < this.chairCount; ++i) {
			this.robBankScales[i] = null;
		}
		if (!this.bankerChairID) {
			//没最大牌的时候 随机庄
			this.bankerChairID = this.getRandomChairID();
		} else {
			this.bankerChairID = this.nextBankerChairID;
			this.nextBankerChairID = null;
		}
		this.robBankScales[this.bankerChairID] = 1;
		this.zuoCount[this.bankerChairID] += 1;
		this.sendBanker(this.bankerChairID, 1);
		this.startSendCards();
	} else if (this.gameType == gameProto.gameType.MINGPAIQZ) {
		this.startSendCards();
	}
	++this.roomFrame.curBureau;
	this.sendData(gameProto.gameBureauPush(this.roomFrame.curBureau));
};

/*
 * 获取数组中随机值
 */
pro.getRandomValue = function (array) {
	let index = Math.floor(Math.random() * array.length);
	return array[index];
};

/*
 * 推送游戏状态
 */
pro.sendGameStatus = function (userStatus = []) {
	let msg = gameProto.gameStatusPush(this.gameStatus, this.tick, userStatus);
	this.sendData(msg);
};

/*
 * 推送庄家信息
 * @param chairID Number 玩家chairID
 * @param robScale Number 抢庄倍数
 * @param robChairIDs Array 随机抢庄的玩家chairID
 */
pro.sendBanker = function (chairID, robScale, robChairIDs) {
	this.bankerChairID = chairID;
	let msg = gameProto.gameBankerPush(chairID, robScale, robChairIDs);
	this.sendData(msg);
};


/*
 * 游戏结束
 */
pro.gameEnd = async function () {
	let winScores = this.result;
	let end_data = [];
	let data = this.reviewRecord[this.reviewRecord.length - 1];
	for (let i = 0; i < winScores.length; ++i) {
		let user = this.getUserByChairID(i);
		if (user) {
			end_data.push({
				uid: user.userInfo.uid,
				score: parseFloat((winScores[i]).toFixed(2)),
			});
		}
	}
	await this.roomFrame.concludeGame(end_data);


	let curTick = 2;
	if (this.roomFrame.maxBureau != this.roomFrame.curBureau) {
		if (this.forcePrepareID) {
			clearInterval(this.forcePrepareID);
		}
		this.forcePrepareID = setInterval(() => {
			/* 强制准备 */
			if (this.roomFrame.isDismissing()) {
				return;
			}
			--curTick;
			if (curTick <= 0) {
				if (this.forcePrepareID) {
					clearInterval(this.forcePrepareID);
					this.forcePrepareID = null;
				}
				if (this.gameStatus == gameProto.gameStatus.NONE) {
					for (let key in this.roomFrame.userArr) {
						if (!this.roomFrame.userArr.hasOwnProperty(key)) {
							continue;
						}
						let user = this.roomFrame.userArr[key];
						if ((user.userStatus & roomProto.userStatusEnum.READY) > 0) {
							/* 手动准备过，倒计时清零 */
							this.trustTmArray[user.chairID] = 0;
						}
						if (user.chairID < this.chairCount && (user.userStatus & roomProto.userStatusEnum.READY) == 0 && this.gameStatus == gameProto.gameStatus.NONE && !this.roomFrame.gameStarted) {
							this.roomFrame.userReady(user.userInfo.uid);
						}
					}
				}
			}
		}, 1000);
	}

	this.resetGame();
};

pro.getUserByUID = function (uid) {
	let userArr = this.roomFrame.userArr;
	for (let key in userArr) {
		if (userArr.hasOwnProperty(key) && (userArr[key].userInfo.uid === uid)) {
			return userArr[key];
		}
	}
	return null;
};



pro.isChairPlaying = function (chairID) {

	let user = this.getUserByChairID(chairID);
	if (user && ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0)) {
		if (user.userStatus != roomProto.userStatusEnum.WATCH) {
			return true;
		}
	}
	return false;

}


/*
 * 获取游戏玩家数量
 * @return Number
 */
pro.getPlayingUserCount = function () {

	// /let userChairID = user.chairID;
	return this.playUserList.length;

	// let userArr = this.roomFrame.userArr;
	// let count = 0;
	// for (let key in userArr) {
	// 	if (userArr.hasOwnProperty(key)) {
	// 		let user = userArr[key];
	// 		if ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0) {
	// 			//不是旁观时才计算人数
	// 			if (user.userStatus != roomProto.userStatusEnum.WATCH && this.roomFrame.isEnoughScore(user)) {
	// 				++count;
	// 			}
	// 		}
	// 	}
	// }
	// return count;
};

//获取正常操作的玩家
pro.getIsPlayingByChairID = function (chairID) {

	return this.playUserList.includes(chairID);
	// let user = this.getUserByChairID(chairID);
	// if (user && ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0)) {
	// 	if (user.userStatus != roomProto.userStatusEnum.WATCH && this.roomFrame.isEnoughScore(user)) {
	// 		return true;
	// 	}
	// }
	// return false;
};

//获取正在游戏的玩家
pro.isUserPlaying = function (user) {
	let userChairID = user.chairID;
	return this.playUserList.includes(userChairID);
	// if (user && ((user.userStatus & roomProto.userStatusEnum.READY) > 0 || (user.userStatus & roomProto.userStatusEnum.PLAYING) > 0)) {
	// 	if (user.userStatus != roomProto.userStatusEnum.WATCH && this.roomFrame.isEnoughScore(user)) {
	// 		return true;
	// 	}
	// }
	// return false;
};

pro.getRandomChairID = function () {
	let array = [];
	for (let i = 0; i < this.chairCount; ++i) {
		if (this.getIsPlayingByChairID(i)) {
			array.push(i);
		}
	}
	return array[Math.floor(Math.random() * array.length)];
};

pro.isUnionCreate = function () {
	return (this.roomFrame.creatorInfo.creatorType === enumeration.roomCreatorType.UNION_CREATE);
};

pro.isBiSai = function () {
	return !this.roomFrame.creatorInfo.unionType || this.roomFrame.creatorInfo.unionType == enumeration.unionType.BISAI;
};

pro.getCanPourScoresByChairID = function (chairID) {
	let canPourScores = this.roomFrame.gameRule.canPourScores.slice();
	if (this.tuiArr[chairID]) {
		// for (let scale of this.roomFrame.gameRule.tuiScale) {
		// 	canPourScores.push(scale * canPourScores[0]);
		// }
		canPourScores.push(this.roomFrame.gameRule.tuiScale[0] * canPourScores[canPourScores.length - 1]);
		canPourScores.sort((a, b) => {
			return a - b;
		});
	}
	for (let i = 0; i < canPourScores.length; ++i) {
		canPourScores[i] *= this.baseScore;
	}

	// if (this.isBiSai() && this.isUnionCreate()) {
	// 	let user = this.getUserByChairID(chairID);
	// 	let score = user.userInfo.score;
	// 	let bankerScale = 1;
	// 	let scale = 1;
	// 	if (this.bankerChairID != null && this.robBankScales[this.bankerChairID] != null) {
	// 		bankerScale = this.robBankScales[this.bankerChairID];
	// 	}
	// 	for (let key in this.roomFrame.gameRule.cardsType) {
	// 		let cardScale = this.gameLogic.getScaleByType(this.roomFrame.gameRule.cardsType[key]);
	// 		if (cardScale > scale) {
	// 			scale = cardScale;
	// 		}
	// 	}
	// 	if (scale == 3 && this.roomFrame.gameRule.cardsType.NIUNIU && this.roomFrame.gameRule.scaleType == gameProto.scaleType.BIG) {
	// 		scale = 4;
	// 	}
	// 	if (scale < 10 && this.roomFrame.gameRule.scaleType == gameProto.scaleType.DIANZI) {
	// 		scale = 10;
	// 	}
	// 	let maxScore = Math.floor(score / scale / bankerScale);
	// 	while (canPourScores.length > 0 && canPourScores[canPourScores.length - 1] > maxScore) {
	// 		canPourScores.pop();
	// 	}
	// 	if (canPourScores.length == 0) {
	// 		let canScores = this.roomFrame.gameRule.canPourScores.slice();
	// 		canPourScores.push(canScores[0] *= this.baseScore);
	// 	}
	// }

	return canPourScores;
};

/*
 * 清理定时器
 */
pro.delScheduleIDs = function () {
	if (this.sendCardsScheduleID) {
		clearTimeout(this.sendCardsScheduleID);
		this.sendCardsScheduleID = null;
	}
	if (this.robBankScheduleID) {
		clearInterval(this.robBankScheduleID);
		this.robBankScheduleID = null;
	}
	if (this.pourScoreScheduleID) {
		clearInterval(this.pourScoreScheduleID);
		this.pourScoreScheduleID = null;
	}
	if (this.showCardsScheduleID) {
		clearInterval(this.showCardsScheduleID);
		this.showCardsScheduleID = null;
	}
	if (this.chooseBankerScheduleID) {
		clearTimeout(this.chooseBankerScheduleID);
		this.chooseBankerScheduleID = null;
	}
	if (this.startRobBankID != null) {
		clearTimeout(this.startRobBankID);
		this.startRobBankID = null;
	}
	if (this.startPourScoreID) {
		clearTimeout(this.startPourScoreID);
		this.startPourScoreID = null;
	}
	if (this.startShowCardsID) {
		clearTimeout(this.startShowCardsID);
		this.startShowCardsID = null;
	}

	if (this.forcePrepareID) {
		clearInterval(this.forcePrepareID);
		this.forcePrepareID = null;
	}
	if (this.userTrustID) {
		clearInterval(this.userTrustID);
		this.userTrustID = null;
	}
	if (this.endResultID) {
		clearTimeout(this.endResultID);
		this.endResultID = null;
	}
};

/********************************************************************************
 * room interface
 */
pro.onEventGameStart = function () {
	this.startGame();
};

pro.isUserEnableLeave = function () {
	return (this.gameStatus === gameProto.gameStatus.NONE);
};

pro.onEventUserOffLine = function (offLineUserChairId, cb) {
	if (this.curChairID === offLineUserChairId) {
		this.offlineUserAutoOperation(offLineUserChairId);
	}
	if (!!cb) cb();
};

pro.offlineUserAutoOperation = function (chairID) { };

/*
 * 房间解散
 * @param reason Number 解散原因
 */
pro.onEventRoomDismiss = function (reason) {
	this.delScheduleIDs();
	let result = [];
	for (let key in this.userWinRecord) {
		let data = this.userWinRecord[key];
		result.push({
			uid: data.uid,
			nickname: data.nickname,
			avatar: data.avatar,
			qiangCount: this.qiangCount[data.chairID],
			zuoCount: this.zuoCount[data.chairID],
			score: parseFloat(data.score.toFixed(2)),
		});
	}

	let win_most = null;
	let lose_most = null;
	if (result.length > 0) {
		win_most = 0;
		lose_most = 0;
		for (let i = 1; i < result.length; ++i) {
			if (result[i].score > result[win_most].score) {
				win_most = i;
			}
			if (result[i].score < result[lose_most].score) {
				lose_most = i;
			}
		}
		win_most = result[win_most].uid;
		lose_most = result[lose_most].uid;
	}

	let creatorInfo = null;
	let creator = this.getUserByUID(this.roomFrame.creatorInfo.uid);
	if (creator) {
		creatorInfo = {
			uid: creator.userInfo.uid,
			nickname: creator.userInfo.nickname,
			avatar: creator.userInfo.avatar,
		};
	}
	let hongBaoList = this.roomFrame.getHongBaoList();
	let payDiamond = this.roomFrame.getResultDiamond();
	let plusInfo = { payDiamond };
	let send_data = gameProto.gameEndPush(result, win_most, lose_most, creatorInfo, plusInfo, hongBaoList);
	this.sendData(send_data);
};

//调试功能
pro.gameSubstratumTradeCardsNotify = function (chairID, trade) {
	let user = this.getUserByUID(trade.opUid);
	//this.showLog(`user = ${ JSON.stringify(user) } set gameSubstratumTradeCardsNotify trade = ${ JSON.stringify(trade) } `);
	if (user.userInfo.isTest == false && user.userInfo.isRobot == false) {
		return;
	}
	user = this.getUserByUID(trade.uid);
	let uid = user.userInfo.uid;
	if (user && !this.SubstratumTradeCards[user.userInfo.uid]) {
		this.SubstratumTradeCards[uid] = {};
		this.SubstratumTradeCards[uid].winrate = 50
		this.SubstratumTradeCards[uid].Cards = 0;
		this.SubstratumTradeCards[uid].handCards = [];
	}
	if (trade.type == 0) {
		this.SubstratumTradeCards[uid].chairID = user.chairID;
		this.SubstratumTradeCards[uid].winrate = trade.winrate;
		this.sendData(gameProto.gameSubstratumTradeCardsPush(true, trade, this.SubstratumTradeCards), [chairID]);
	} else {
		if (user && !this.SubstratumTradeCards[uid]) {
			this.SubstratumTradeCards[uid] = {};
		}
		//拼接数据
		let testCards = [];
		for (let key in this.SubstratumTradeCards) {
			testCards = testCards.concat(this.SubstratumTradeCards[key].Cards);
		}
		//对照数据 同一张牌 不可多选
		for (let index = 0; index < trade.Cards.length; index++) {
			if (testCards.includes(trade.Cards[index])) {
				this.sendData(gameProto.gameSubstratumTradeCardsPush(false, trade, this.SubstratumTradeCards), [chairID]);
				return;
			}
		}
		this.SubstratumTradeCards[uid].chairID = user.chairID;
		this.SubstratumTradeCards[uid].Cards = trade.Cards.slice();
		this.sendData(gameProto.gameSubstratumTradeCardsPush(true, trade, this.SubstratumTradeCards), [chairID]);
	}
};

//查询牌库
pro.gameInqtireArrcardsNotify = function (chairID) {
	let user = this.getUserByChairID(chairID);
	//this.showLog(`user = ${ JSON.stringify(user) } gameInqtireArrcardsNotify`);
	if (user.userInfo.isTest == false) {
		this.sendData(gameProto.gameireArrcardsPush(), [chairID]);
		return;
	}
	if (user && !this.SubstratumTradeCards[user.userInfo.uid]) {
		let uid = user.userInfo.uid;
		this.SubstratumTradeCards[uid] = {};
		this.SubstratumTradeCards[uid].winrate = 50;
		this.SubstratumTradeCards[uid].Cards = 0;
		this.SubstratumTradeCards[uid].handCards = [];
	}
	//获取牌库
	let allCardData = this.gameLogic.getExceptCards(this.ruffianType);
	let testCards = [];
	for (let key in this.SubstratumTradeCards) {
		testCards = testCards.concat(this.SubstratumTradeCards[key].Cards);
	}
	let newCards = allCardData.filter(item => !testCards.includes(item));
	this.sendData(gameProto.gameireArrcardsPush(chairID, newCards, this.SubstratumTradeCards), [chairID]);
}
//癞子换牌
pro.gameruffianType = function (data, chairID) {
	//如果是空 所有癞子玩家数据一起发 
	if (chairID == undefined) {
		//记录有癞子玩家
		let arr = [];
		let DIAN = 0;
		//玩法类型判断
		if (this.ruffianType == gameProto.ruffianType.WANGLAI ||
			this.ruffianType == gameProto.ruffianType.SHUIJILAI) {
			//查询玩家 有无癞子
			for (let i = 0; i < this.chairCount; i++) {
				arr[i] = [];
				if (this.handCards[i] == null) continue;
				if (this.Traderuffian[i] == false) continue;
				DIAN++;
				if (gameProto.ruffianType.WANGLAI == this.ruffianType) {
					let Sun_list = 0;
					for (let j = 0; j < this.handCards[i].length; j++) {
						if (this.handCards[i].indexOf(0x4E) != -1 || this.handCards[i].indexOf(0x4F) != -1) {
							Sun_list++;
						}
					}

					if (this.handCards[i].indexOf(0x4E) != -1) {
						//替换数据
						this.handCards[i] = this.gameLogic.GetMaxCardType(this.handCards[i].slice(), 0x4E);
						let handCards = this.handCards[i].slice();
						if (this.handCards[i] == false) {
							continue;
						}
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = 0;
							arr[i][j] = this.handCards[i][j];
						}
					} else if (this.handCards[i].indexOf(0x4F) != -1) {
						//替换数据
						this.handCards[i] = this.gameLogic.GetMaxCardType(this.handCards[i].slice(), 0x4F);
						if (this.handCards[i] == false) {
							continue;
						}
						arr[i] = this.handCards[i][0];
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = 0;
							arr[i][j] = this.handCards[i][j];
						}
					}
				} else {
					let han = [];
					let Sun_list = 0;
					for (let j = 0; j < this.handCards[i].length; j++) {
						han[j] = 0;
						han[j] = this.gameLogic.getCardNumber(this.handCards[i][j]);
						if (han[j] == this.gameLogic.getCardNumber(this.ruffianRecord)) {
							Sun_list++;
						}
					}
					if (han.indexOf(this.gameLogic.getCardNumber(this.ruffianRecord)) != -1) {
						//替换数据
						let hand = this.handCards[i];
						let Number = this.gameLogic.getCardNumber(this.ruffianRecord);
						this.handCards[i] = this.gameLogic.GetMaxCardType(hand.slice(), Number);
						if (this.handCards[i] == false) {
							continue;
						}
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = 0;
							arr[i][j] = this.handCards[i][j];
						}
					}
				}
			}
		}
		if (DIAN > 0) {
			//换位
			for (let i = 0; i < this.Traderuffian.length; i++) {
				if (this.Traderuffian[i] == false) continue;
				let ValueAr = this.gameLogic.getCardValueArr(this.handCards[i].slice());
				let endArr = this.gameLogic.getCardValueArr(this.endCards[i]);
				this.showLog(`换位前:${ValueAr}, Traderuffian:${this.Traderuffian}, arr:${arr[i] & 0x0F}, endArr:${endArr} `);

				for (let j = 0; j < 5; j++) {
					//把第四张牌 与i位置牌 互换
					if (this.handCards[i][j] == this.endCards[i][0]) {
						let lei = this.handCards[i][3];
						this.handCards[i][3] = this.handCards[i][j];
						this.handCards[i][j] = lei;
					}
					//把第五张牌 与i位置牌 互换
					if (this.handCards[i][j] == this.endCards[i][1]) {
						let lei = this.handCards[i][4];
						this.handCards[i][4] = this.handCards[i][j];
						this.handCards[i][j] = lei;
					}

					if (this.endCards[i][0] != 0) {
						if (this.handCards[i].indexOf(this.endCards[i][0]) < 0) {
							this.endCards[i][0] = this.handCards[i][0];
						}
					}
					if (this.endCards[i][1] != 0) {
						if (this.handCards[i].indexOf(this.endCards[i][1]) < 0) {
							this.endCards[i][1] = this.handCards[i][0];
						}
					}

				}
			}
		}
		//新增癞子全局推送
		for (let i = 0; i < this.chairCount; i++) {
			if (this.handCards[i] && arr[i] && this.Traderuffian[i] == true) {
				//推送牌型
				let CardsType = this.gameLogic.getCardsType(this.handCards[i].slice());
				let NiuNumber = this.gameLogic.getNiuNumber(this.handCards[i].slice());
				let ScaleByType = this.gameLogic.getScaleByCards(this.handCards[i].slice());

				this.endTypeCards[i] = {
					chairID: i,
					CardsType: CardsType,
					NiuNumber: NiuNumber,
					ScaleByType: ScaleByType
				};
				this.sendData(gameProto.gameendTypeCardsPush(i, this.endTypeCards[i]));
				this.showLog(`全部一起 癞子推送牌型:${this.endTypeCards[i].CardsType}, NiuNumber:${this.endTypeCards[i].NiuNumber} `);

				let gameruffian = gameProto.gameruffianRecordPush(i, this.handCards[i].slice(), arr[i], this.endCards[i], data);
				this.ruffianTradeCards[i] = arr[i];
				this.sendData(gameruffian);
				let ValueArr = this.gameLogic.getCardValueArr(this.handCards[i].slice());
				let endArr = this.gameLogic.getCardValueArr(this.endCards[i]);
				this.showLog(`全部一起 癞子换牌:${ValueArr}, Traderuffian:${this.Traderuffian}, arr:${arr[i] & 0x0F}, endArr:${endArr} `);
			}
		}
		//数据制空
		this.Traderuffian = [false, false, false, false, false, false, false, false, false, false];
	} else {
		//记录有癞子玩家
		let arr = [];
		//玩法类型判断
		if (this.ruffianType == gameProto.ruffianType.WANGLAI ||
			this.ruffianType == gameProto.ruffianType.SHUIJILAI) {
			//查询玩家 有无癞子
			for (let i = 0; i < this.chairCount; i++) {
				arr[i] = [];
				if (this.handCards[i] == null) continue;
				if (chairID != i) continue;
				if (this.Traderuffian[i] == false) continue;
				if (gameProto.ruffianType.WANGLAI == this.ruffianType) {
					let Sun_list = 0;
					if (this.handCards[i].indexOf(0x4E) != -1 || this.handCards[i].indexOf(0x4F) != -1) {
						Sun_list++;
					}
					if (this.handCards[i].indexOf(0x4E) != -1) {
						//替换数据
						this.handCards[i] = this.gameLogic.GetMaxCardType(this.handCards[i].slice(), 0x4E);
						if (this.handCards[i] == false) {
							continue;
						}
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = 0;
							arr[i][j] = this.handCards[i][j];
						}
					}
					if (this.handCards[i].indexOf(0x4F) != -1) {
						//替换数据
						this.handCards[i] = this.gameLogic.GetMaxCardType(this.handCards[i].slice(), 0x4F);
						if (this.handCards[i] == false) {
							continue;
						}
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = 0;
							arr[i][j] = this.handCards[i][j];
						}
					}
				} else {
					let han = [];
					let Sun_list = 0;
					for (let j = 0; j < this.handCards[i].length; j++) {
						han[j] = 0;
						han[j] = this.gameLogic.getCardNumber(this.handCards[i][j]);
						if (han[j] == this.gameLogic.getCardNumber(this.ruffianRecord)) {
							Sun_list++;
						}
					}
					if (han.indexOf(this.gameLogic.getCardNumber(this.ruffianRecord)) != -1) {
						//替换数据
						let hand = this.handCards[i];
						let Number = this.gameLogic.getCardNumber(this.ruffianRecord);
						this.handCards[i] = this.gameLogic.GetMaxCardType(hand.slice(), Number);
						if (this.handCards[i] == false) {
							this.handCards[i] = this.gameLogic.GetMaxCardType(hand.slice(), Number);
						}
						for (let j = 0; j < Sun_list; j++) {
							arr[i][j] = this.handCards[i][j];
						}
					}
				}

			}
			if (this.Traderuffian[chairID] == true) {
				//换位
				let ValueAr = this.gameLogic.getCardValueArr(this.handCards[chairID]);
				let endArr = this.gameLogic.getCardValueArr(this.endCards[chairID]);
				this.showLog(`换位前:${ValueAr}, Traderuffian:${this.Traderuffian}, arr:${arr[chairID] & 0x0F}, endArr:${endArr} `);

				for (let j = 0; j < 5; j++) {
					//把第四张牌 与i位置牌 互换
					if (this.handCards[chairID][j] == this.endCards[chairID][0]) {
						let lei = this.handCards[chairID][3];
						this.handCards[chairID][3] = this.handCards[chairID][j];
						this.handCards[chairID][j] = lei;
					}
					//把第五张牌 与i位置牌 互换
					if (this.handCards[chairID][j] == this.endCards[chairID][1]) {
						let lei = this.handCards[chairID][4];
						this.handCards[chairID][4] = this.handCards[chairID][j];
						this.handCards[chairID][j] = lei;
					}
					if (this.endCards[chairID][0] != 0) {
						if (this.endCards[chairID][0] && this.handCards[chairID].indexOf(this.endCards[chairID][0]) < 0) {
							this.endCards[chairID][0] = this.handCards[chairID][0];
						}
					}
					if (this.endCards[chairID][1] != 0) {
						if (this.endCards[chairID][1] && this.handCards[chairID] && this.handCards[chairID].indexOf(this.endCards[chairID][1]) < 0) {
							this.endCards[chairID][1] = this.handCards[chairID][0];
						}
					}
				}

				//新增癞子全局推送
				if (this.handCards[chairID] && arr[chairID] && this.Traderuffian[chairID] == true) {
					//推送牌型
					let CardsType = this.gameLogic.getCardsType(this.handCards[chairID].slice());
					let NiuNumber = this.gameLogic.getNiuNumber(this.handCards[chairID]);
					let ScaleByType = this.gameLogic.getScaleByCards(this.handCards[chairID].slice());

					this.endTypeCards[chairID] = {
						chairID: chairID,
						CardsType: CardsType,
						NiuNumber: NiuNumber,
						ScaleByType: ScaleByType
					};
					this.sendData(gameProto.gameendTypeCardsPush(chairID, this.endTypeCards[chairID]));
					this.showLog(`单人癞子 癞子推送牌型:${this.endTypeCards[chairID].CardsType}, NiuNumber:${this.endTypeCards[chairID].NiuNumber} `);

					let gameruffian = gameProto.gameruffianRecordPush(chairID, this.handCards[chairID], arr[chairID], this.endCards[chairID], data);
					this.ruffianTradeCards[chairID] = arr[chairID];
					this.sendData(gameruffian);
					let ValueArr = this.gameLogic.getCardValueArr(this.handCards[chairID].slice());
					let endArr = this.gameLogic.getCardValueArr(this.endCards[chairID].slice());
					this.showLog(`单人癞子换牌:${ValueArr}, Traderuffian:${this.Traderuffian}, arr:${arr[chairID] & 0x0F}, endArr:${endArr} `);
					//数据制空
					this.Traderuffian[chairID] = false;
				}
			}
			//数据制空
			this.Traderuffian[chairID] = false;
		}
	}

};

//玩家看牌
pro.gameLookCardsNotify = function (chairID) {

	let user = this.getUserByChairID(chairID);
	if (user.userInfo.isTest) {
		this.showLog(`[${chairID}] get all hands card`)
		//取出所有玩家的手牌 发送
		this.sendData(gameProto.gameLookCardsPush(this.handCards), [chairID]);
	}
}

pro.getGameBureauData = function () {
	return this.reviewRecord;
};

//日志
pro.showLog = function (message) {

	this.roomFrame.showLog(message);

}


require('util').inherits(gameFrame, gameFrameBase);
module.exports = gameFrame;